package com.sumer.psychology.photo.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.sumer.psychology.photo.application.command.DeletePhotosCommand;
import com.sumer.psychology.photo.application.command.PhotoApplicationService;
import com.sumer.psychology.photo.infrastructure.persistence.mongo.MongoAlbumRepository;
import org.apache.commons.lang3.StringUtils;

/**
 * 监听相册删除事件
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/29
 * Time: 16:18
 */
public class AlbumDeletedEventListener extends ExchangeListener {
    private PhotoApplicationService photoApplicationService;
    private MongoAlbumRepository mongoAlbumRepository;

    public AlbumDeletedEventListener(
            PhotoApplicationService photoApplicationService,
            MongoAlbumRepository mongoAlbumRepository) {
        this.photoApplicationService = photoApplicationService;
        this.mongoAlbumRepository = mongoAlbumRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String albumId = reader.eventStringValue("albumId.identity");

        if (StringUtils.isNotBlank(albumId)) {
            photoApplicationService().deleteAllOfAlbum(
                    new DeletePhotosCommand(albumId));

            mongoAlbumRepository().removeOne(albumId);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.photo.domain.model.AlbumDeletedEvent"};
    }

    private PhotoApplicationService photoApplicationService() {
        return photoApplicationService;
    }

    private MongoAlbumRepository mongoAlbumRepository() {
        return mongoAlbumRepository;
    }
}
